package actions;

import java.util.ArrayList;

import javax.ejb.EJB;

import beans.UserManager;
import beans.UserManagerLocal;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;

public class AddFriendAction extends ActionSupport {

	private Integer[] isChecked;
	private boolean addfriend = false;
	private boolean addanti = false;

	@EJB
	private UserManagerLocal userMgr;

	public String execute() {

		userMgr = new UserManager();
		Integer userIdObj = (Integer) ActionContext.getContext().getSession()
				.get("userId");
		if (userIdObj == null) {
			this.addActionError("UserID is null");
			return ERROR;
		}

		if (addfriend) {
			if (isChecked != null && isChecked.length == 1) {
				this.addActionMessage("No friend checked.");
			}
			ArrayList<Integer> failures = userMgr.makeFriend(isChecked,
					userIdObj);
			if (!(failures.isEmpty())) {
				String message = "Failed IDs: ";
				for (int i = 0; i < failures.size(); i++) {
					message += failures.get(i).intValue() + " ";
				}
				this.addActionError(message);
			} else {
				return SUCCESS;
			}
		} else if (addanti) {
			if (isChecked != null && isChecked.length == 1) {
				this.addActionMessage("No antifriend checked.");
			}
			ArrayList<Integer> failures = userMgr.makeAntifriend(isChecked,
					userIdObj);
			if (!(failures.isEmpty())) {
				String message = "The following friend still remain friends: ";
				for (int i = 0; i < failures.size(); i++) {
					message += failures.get(i).intValue() + " ";
				}
				this.addActionError(message);
			} else {
				return SUCCESS;
			}
		}
		return "failedadd";

	}

	public boolean isAddfriend() {
		return addfriend;
	}

	public void setAddfriend(boolean addfriend) {
		this.addfriend = true;
	}

	public boolean isAddanti() {
		return addanti;
	}

	public void setAddanti(boolean addanti) {
		this.addanti = true;
	}

	public Integer[] getIsChecked() {
		return isChecked;
	}

	public void setIsChecked(Integer[] isChecked) {
		this.isChecked = isChecked;
	}

}
